package com.ias.agdis_r.fragment.main;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
//import android.support.v4.app.Fragment;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.more.PhotoAlbumActivity;
import com.ias.agdis_r.activity.more.WifiHotspotActivity;
import com.ias.agdis_r.activity.more.WorkGroupActivity;
import com.ias.agdis_r.bean.auth.AuthEnum;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.sdcard.SDcard;
import com.zbar.lib.CaptureActivity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class More extends Fragment {

    private static final int REQUEST_CODE_QR_CODE = 2;

    private GridView gridview_more;
    private final int ID_CAMERA = 0;
    private final int ID_PHOTOALBUM = 1;
    //	private final int ID_BLUETOOTH = 2;
    private final int ID_WIFI = 3;
    private final int ID_CAlCULATOR = 4;
    private final int ID_PTT = 5;
    private final int ID_QRCODE = 7;
    private final int ID_WORK_GROUP = 8;
    private Context context = DataBaseManager.getInstance().getContext();
    String photo_name = "";

    private ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_more, container, false);
        init(view);
        return view;
    }

    public void init(View view) {
        gridview_more = (GridView) view.findViewById(R.id.gridview_more);

        HashMap<String, Object> map1 = new HashMap<String, Object>();
        map1.put("Id", ID_CAMERA);
        map1.put("ItemImage", R.drawable.menu_camera_icon);//添加图像资源的ID
        map1.put("ItemText", context.getString(R.string.camera));

        HashMap<String, Object> map2 = new HashMap<String, Object>();
        map2.put("Id", ID_PHOTOALBUM);
        map2.put("ItemImage", R.drawable.menu_photoalbum_icon);//添加图像资源的ID
        map2.put("ItemText", context.getString(R.string.gallery));

//		 HashMap<String, Object> map3 = new HashMap<String, Object>();
//	     map3.put("Id", ID_BLUETOOTH);
//	     map3.put("ItemImage", R.drawable.menu_bluetooth_icon);//添加图像资源的ID
//		 map3.put("ItemText", "蓝牙");

//		 HashMap<String, Object> map4 = new HashMap<String, Object>();
//	     map4.put("Id", ID_WIFI);
//	     map4.put("ItemImage", R.drawable.menu_wifi_icon);//添加图像资源的ID
//		 map4.put("ItemText", "热点管理");

        HashMap<String, Object> map5 = new HashMap<String, Object>();
        map5.put("Id", ID_CAlCULATOR);
        map5.put("ItemImage", R.drawable.menu_calculator_icon);//添加图像资源的ID
        map5.put("ItemText", getString(R.string.calculator));

        HashMap<String, Object> map6 = new HashMap<String, Object>();
        map6.put("Id", ID_PTT);
        map6.put("ItemText", getString(R.string.ptt));
        if (S.checkAppInstall("ias.mmv")){
            map6.put("ItemImage", R.drawable.menu_mmv_icon);//添加图像资源的ID
        }else if (S.checkAppInstall("com.corget")){
            map6.put("ItemImage", R.drawable.menu_ptt_icon);//添加图像资源的ID
        }else{
            map6 = null;
        }

        HashMap<String, Object> map7 = new HashMap<String, Object>();
        map7.put("Id", ID_QRCODE);
        map7.put("ItemImage", R.drawable.barcode_scanner);//添加图像资源的ID
        map7.put("ItemText", getString(R.string.scan));

        lstImageItem.add(map1);
        lstImageItem.add(map2);
//		 lstImageItem.add(map3);
//		 lstImageItem.add(map4);
        lstImageItem.add(map5);
        if (null != map6){
            lstImageItem.add(map6);
        }
        lstImageItem.add(map7);

        HashMap<String, Object> map8 = new HashMap<String, Object>();
        map8.put("Id", ID_WORK_GROUP);
        map8.put("ItemImage", R.drawable.work_group);//添加图像资源的ID
        map8.put("ItemText", getString(R.string.work_group));
        lstImageItem.add(map8);

        SimpleAdapter saImageItems = new SimpleAdapter(
                getActivity(), lstImageItem, R.layout.item_more_grid,
                new String[]{"ItemImage", "ItemText"},
                new int[]{R.id.img_item, R.id.text_item});
        //添加并且显示
        gridview_more.setAdapter(saImageItems);
        //添加消息处理
        gridview_more.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // TODO Auto-generated method stub
                HashMap<String, Object> map = lstImageItem.get(position);

                int mapid = (int) map.get("Id");
                switch (mapid) {
                    case ID_CAMERA:
                        //如果有照相权限
                        if (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_CAMERA.toString())) {
                            startCamera();
                        } else {
                            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO, context.getString(R.string.no_AI_T_CAMERA), false);
                        }
                        break;
                    case ID_PHOTOALBUM:
                        //如果有照相权限
                        if (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_CAMERA.toString())) {
                            startPhotoAlbum();
                        } else {
                            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO, context.getString(R.string.no_AI_T_CAMERA2), false);
                        }
                        break;
//					  case ID_BLUETOOTH:
//			       		 	startBluetoothSetting();
//			       	 		break;
                    case ID_WIFI:
                        startWifiHotspot();
                        break;
                    case ID_CAlCULATOR:
                        startCalculator();
                        break;
                    case ID_PTT:
                        startPtt();
                        break;
                    case ID_QRCODE:
                        startQrCode();
                        break;
                    case ID_WORK_GROUP:
                        if (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_WORKGROUP.toString())) {
                            startWorkGroup();
                        } else {
                            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO, context.getString(R.string.no_AI_T_WORKGROUP), false);
                        }
                        break;
                }

            }

        });
    }


    /**
     * 启动扫描二维码
     */
    private void startQrCode() {
        Intent intent = new Intent(getActivity(), CaptureActivity.class);
        startActivityForResult(intent, REQUEST_CODE_QR_CODE);

        //小米二维码扫描启动方式，成功后返回intent中result为扫描结果
//        Intent intent = new Intent();
//        intent.setClassName("com.miui.barcodescanner","com.miui.barcodescanner.activity.CaptureActivity");
//        intent.putExtra("isBackToThirdApp", true);
//        intent.putExtra("fromApp", "AGDIS");
//        startActivityForResult(intent, REQUEST_CODE_QR_CODE);
    }

    /** 启动班组列表 */
    private void startWorkGroup() {
        Intent intent = new Intent(getActivity(), WorkGroupActivity.class);
        startActivity(intent);
    }

    private void startPtt() {
        Intent intent = null;
        if (S.checkAppInstall("ias.mmv")){
            intent = runAppActivity("ias.mmv");
//            intent.setClassName("ias.mmv", "ias.mmv.activity.StartActivity");
        }else if (S.checkAppInstall("com.corget")){
            intent = runAppActivity("com.corget");
            if (null != intent){
                intent.putExtra("com.corget.MainView.extra.group_selector_auto_open", true);
            }
//            intent.setClassName("com.corget", "com.corget.MainView");
//            intent.putExtra("com.corget.MainView.extra.group_selector_auto_open", true);
        }
        try {
            if (null != intent){
                startActivity(intent);
            }
        } catch (Exception e) {
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, DataBaseManager.getInstance().getContext().getString(R.string.ptt_failed), false);
        }
    }

    /**
     * 启动蓝牙设置界面
     */
//	public void startBluetoothSetting(){
//
//		getActivity().startActivity(
//				new Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS));
//	}

    /**
     * 启动手机拍照界面
     */
    public void startCamera() {

        if (!SDcard.isFileExist(DataBaseManager.PHOTO_FORDER_PATH)) {// 如果目录不存在，则创建目录
            SDcard.creatSDDir(DataBaseManager.PHOTO_FORDER_PATH);
        }

        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.addCategory("android.intent.category.DEFAULT");
        photo_name = S.getPhotoName("");
        String photoPath = DataBaseManager.PHOTO_FORDER_PATH + photo_name;
        File file = new File(photoPath);
        Uri uri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, 1);
    }

    /**
     * 启动系统手机图库
     */
    public void startPhotoAlbum() {

        Intent intent = new Intent(getActivity(), PhotoAlbumActivity.class);
        startActivity(intent);
    }

    /**
     * 启动WIFI热点页面
     */
    public void startWifiHotspot() {

        Intent intent = new Intent(getActivity(), WifiHotspotActivity.class);
        startActivity(intent);
    }

    /**
     * 启动系统计算器
     */
    public void startCalculator() {

        Intent intent = new Intent();
        intent.setClassName("com.android.calculator2",
                "com.android.calculator2.Calculator");
        startActivity(intent);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1 && resultCode != Activity.RESULT_CANCELED) {
            //保存缩略图
            makeImageThumbnails();
            //重新启动相机
            //如果有照相权限
            if (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_CAMERA.toString())) {
                startCamera();
            } else {
                EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO, context.getString(R.string.no_AI_T_CAMERA), false);
            }
        }

        if (requestCode == REQUEST_CODE_QR_CODE && resultCode == Activity.RESULT_OK) {
            String code = data.getStringExtra("data");
            if(S.isEmpty(code)){
                code = data.getStringExtra("result");
            }
            handleQrCode(code);
        }
    }

    private void handleQrCode(String code) {
        Toast.makeText(getActivity(), getString(R.string.scanResult) + code, Toast.LENGTH_LONG).show();
    }

    /**
     * 保存照片缩略图
     */
    public void makeImageThumbnails() {
        BufferedOutputStream bos = null;
        Bitmap bitmap = null;
        try {
            if (S.isEmpty(photo_name)) {
                return;
            }
            String photoPath = DataBaseManager.PHOTO_FORDER_PATH + photo_name;
            File file = new File(photoPath);
            //如果没有图片文件，返回
            if (!file.exists()) {
                return;
            }
            String thumbnails_path = DataBaseManager.DCIM_FORDER_PATH + photo_name;
            //如果目录不存在创建目录
            if (!SDcard.isFileExist(DataBaseManager.DCIM_FORDER_PATH)) {
                SDcard.creatSDDir(DataBaseManager.DCIM_FORDER_PATH);
            }
            //生成缩略图
            if (!SDcard.isFileExist(thumbnails_path)) {

                SDcard.creatSDFile(thumbnails_path);
            }
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true; // 设为 false
            bitmap = BitmapFactory.decodeFile(photoPath, options);
            options.inJustDecodeBounds = false; // 设为 false
            // 计算缩放比
            int h = options.outHeight;
            int w = options.outWidth;
            int beWidth = w / 90;
            int beHeight = h / 90;
            int be = 1;
            if (beWidth < beHeight) {
                be = beWidth;
            } else {
                be = beHeight;
            }
            if (be <= 0) {
                be = 1;
            }
            options.inSampleSize = be;
            // 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
            bitmap = BitmapFactory.decodeFile(photoPath, options);
            bos = new BufferedOutputStream(new FileOutputStream(thumbnails_path));
            //OutputStream os = new FileOutputStream(myCaptureFile);
            /* 采用压缩转档方法 */
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
			/* 调用flush()方法，更新BufferStream */
            bos.flush();
						
			/* 结束OutputStream */
            bos.close();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();
            }
        }

    }

    public Intent runAppActivity(String packName) {
        PackageInfo pi;
        try {
            pi = getActivity().getPackageManager().getPackageInfo(packName, 0);
            Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
            resolveIntent.setPackage(pi.packageName);
            PackageManager pManager = getActivity().getPackageManager();
            List<ResolveInfo> apps = pManager.queryIntentActivities(
                    resolveIntent, 0);
            if (apps.size() == 0) {
                //如果没有ACTIVITY返回
                return null;
            }
            ResolveInfo ri = apps.iterator().next();
            Intent intent = null;
            if (ri != null) {
                intent = new Intent(Intent.ACTION_MAIN);
                packName = ri.activityInfo.packageName;
                String className = ri.activityInfo.name;
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                ComponentName cn = new ComponentName(packName, className);
                intent.setComponent(cn);
            }
            return intent;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}